package connection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Connection extends Thread {

	private String host = "localhost";
	private int port = 30456;
	
	private boolean running;
	
	private DataOutputStream output;
	
	private Socket socket;
	
	@Override
	public void run() {
		try {
			socket = new Socket(host, port);
			
			DataInputStream input = new DataInputStream(socket.getInputStream());
			output = new DataOutputStream(socket.getOutputStream());
			
			running = true;
			while(running) {
				String s = input.readUTF();
				
				incomingMessage(s);
			}
			
		} catch(ConnectException e) {
			System.out.println("Cannot connect to server");
		} catch (UnknownHostException e) {
			//e.printStackTrace();
		} catch (EOFException e) {
			System.out.println("Disconnect from server");
		} catch (IOException e) {
			//e.printStackTrace();
		}
	}
	
	private void incomingMessage(String message) {
		System.out.println("incoming: " + message);
	}
	
	public void sendMessage(String message) {
		try {
			System.out.println("send: " + message);
			output.writeUTF(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		if(socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public boolean isRunning() {
		return running;
	}
}
